import { loginAPI, fetchUserInfoAPI } from '@/api/user/userApi'
import { getToken, removeToken, setToken } from '@/utils/auth'

const actions = {
  /* 发送登录请求的action */
  async userLogin(context, loginForm) {
    const { data: { token } } = await loginAPI(loginForm)
    context.commit('setToken', token)
    return '登录成功'
  },
  /* 退出登录的action */
  async userLogout(context) {
    context.commit('removeToken')
    return '退出成功'
  },
  /* 发送请求获取用户信息的action */
  async fetchUserInfo(context) {
    const { data } = await fetchUserInfoAPI()
    context.commit('updateUserInfo', data)
    return { menus: data.menus, permissions: data.permissions }
  }
}
const mutations = {
  /* 设置token的mutation */
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  /* 移除token的mutation */
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  /* 更新用户信息的mutation */
  updateUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
}
const state = () => {
  return {
    token: getToken() || '',
    userInfo:{}
  }
}

const getters = {}

export default {
  actions,
  mutations,
  state,
  getters,
  namespaced: true
}

